import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/login/index.vue'
import Layout from '../views/layout/index.vue'
import Article from '../views/article/index.vue'
import EditArticle from '../views/article/edit.vue'
import AddArticle from '../views/article/add.vue'
import Comment from '../views/comment/index.vue'
import Image from '../views/image/index.vue'
import Page404 from '../views/page404/index.vue'
import Fans from '@/views/fans'

Vue.use(VueRouter)
const routes = [
  {
    path: '/',
    name: 'Layout',
    component: Layout,
    children: [
      {
        path: '/articles',
        name: 'Articles',
        component: Article
      },
      // 动态路由
      {
        path: '/editArticle/:id',
        name: 'editArticle',
        component: EditArticle
      },
      // 素材管理
      {
        path: '/image',
        name: 'Image',
        component: Image
      },
      // 添加文章
      {
        path: '/addArticle',
        name: 'AddArticle',
        component: AddArticle
      },
      // 评论管理
      {
        path: '/comment',
        name: 'Comment',
        component: Comment
      },
      // 粉丝管理
      {
        path: '/fans',
        name: 'fans',
        component: Fans
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '*',
    name: 'Page404',
    component: Page404
  }
  // {
  //   path: '/about',
  //   name: 'About',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  // }
]

const router = new VueRouter({
  routes
})

// 路由导航守卫
//   所有的路由页面中跳转，都会先进入到这个函数中来。
// to: 要跳入的路由信息。  你要去哪里
// from: 要跳出的路由信息。你从哪里来
// next: 放行方法
//   - next() : 正确跳转。允许进入到 to 路由
//   - next(路由地址) : 不允许去to，而转去指定的路由地址

router.beforeEach((to, from, next) => {
  console.log('路由导航守卫:', to, from, next)
  // 如果你没有登陆，则不让进入 主页
  if (to.path === '/') {
    // 检查是否有token
    const token = localStorage.getItem('tokenStr')
    if (token) {
      next()
    } else {
      // 回登陆页
      alert('没有token，不能访问主页')
      next('/login')
    }
  } else {
    next()
  }
})

export default router
